<template>
  <div class="min-h-screen bg-gradient-to-br from-purple-50 to-indigo-50 p-6">
    <div class="max-w-7xl mx-auto">
      <div class="bg-white/80 backdrop-blur-lg rounded-xl shadow-xl p-6">
        <!-- Header -->
        <div class="flex justify-between items-center mb-6">
          <div class="flex items-center gap-4">
            <button 
              @click="handleGoBack" 
              class="p-2 rounded-lg hover:bg-gray-100"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
            </button>
            <h1 class="text-2xl font-semibold text-gray-800">校对文档</h1>
          </div>
          <div class="flex gap-2">
            <button 
              @click="handleSave"
              :disabled="saving"
              class="px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              <svg v-if="saving" class="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              保存
            </button>
          </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="flex justify-center items-center py-12">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
        </div>

        <!-- Document Content -->
        <div v-else-if="document" class="space-y-6">
          <!-- Title -->
          <div class="border-b pb-4">
            <h2 class="text-xl font-medium text-gray-800">{{ document.title }}</h2>
            <div class="mt-2 flex items-center gap-4 text-sm text-gray-500">
              <span>当前步骤: {{ getStepText(document.step) }}</span>
              <span class="text-green-600 flex items-center gap-1">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                已锁定进行编辑
              </span>
            </div>
          </div>

          <!-- Original Content -->
          <div class="bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-medium text-gray-800 mb-2">原文</h3>
            <div class="whitespace-pre-wrap text-gray-600">{{ document.origin }}</div>
          </div>

          <!-- Edit Area -->
          <div class="bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-medium text-gray-800 mb-2">
              {{ getEditAreaTitle(document.step) }}
            </h3>
            <textarea
              v-model="editContent"
              rows="10"
              class="w-full p-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 resize-none"
              :placeholder="getEditAreaPlaceholder(document.step)"
            ></textarea>
          </div>

          <!-- Previous Checks -->
          <template v-if="document.step > 1">
            <div v-if="document.first_check" class="bg-white rounded-lg shadow p-4">
              <h3 class="text-lg font-medium text-gray-800 mb-2">第一次校对</h3>
              <div class="whitespace-pre-wrap text-gray-600">{{ document.first_check }}</div>
            </div>

            <div v-if="document.second_check && document.step > 2" class="bg-white rounded-lg shadow p-4">
              <h3 class="text-lg font-medium text-gray-800 mb-2">第二次校对</h3>
              <div class="whitespace-pre-wrap text-gray-600">{{ document.second_check }}</div>
            </div>
          </template>
        </div>

        <!-- Error State -->
        <div v-else class="text-center py-12 text-gray-500">
          文档不存在或已被删除
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '../utils/request'
import { ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()
const document = ref(null)
const loading = ref(false)
const saving = ref(false)
const editContent = ref('')
const hasUnlocked = ref(false)

const getStepText = (step) => {
  const steps = {
    0: '未开始',
    1: '第一次校对',
    2: '第二次校对',
    3: '第三次校对'
  }
  return steps[step] || '未知状态'
}

const getEditAreaTitle = (step) => {
  const titles = {
    1: '第一次校对',
    2: '第二次校对',
    3: '第三次校对'
  }
  return titles[step] || '校对内容'
}

const getEditAreaPlaceholder = (step) => {
  const placeholders = {
    1: '请输入第一次校对内容...',
    2: '请输入第二次校对内容...',
    3: '请输入第三次校对内容...'
  }
  return placeholders[step] || '请输入校对内容...'
}

const getCurrentContent = computed(() => {
  if (!document.value) return ''
  const contentMap = {
    1: document.value.first_check,
    2: document.value.second_check,
    3: document.value.third_check
  }
  return contentMap[document.value.step] || ''
})

const fetchDocument = async () => {
  loading.value = true
  try {
    const result = await request.get(`/documents/${route.params.id}`)
    if (result.code === 200) {
      document.value = result.data
      editContent.value = getCurrentContent.value
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
  } finally {
    loading.value = false
  }
}

const unlockDocument = async () => {
  if (hasUnlocked.value || !document.value) return
  
  try {
    const result = await request.post(`/documents/${route.params.id}/unlock`)
    if (result.code === 200) {
      hasUnlocked.value = true
    } else if (result.code === 401) {
      // 认证错误由request.js统一处理
      console.log('解锁时发生认证错误，将重定向到登录页')
    }
  } catch (error) {
    // 捕获错误但不阻止组件卸载流程
    console.error('解锁文档失败:', error)
  }
}

const handleGoBack = async () => {
  if (document.value && editContent.value !== getCurrentContent.value) {
    try {
      await ElMessageBox.confirm(
        '您有未保存的更改，确定要离开吗？',
        '未保存的更改',
        {
          confirmButtonText: '离开',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }
      )
      // 用户确认离开，解锁文档
      await unlockDocument()
      router.back()
    } catch {
      // 用户取消，继续编辑
    }
  } else {
    // 没有更改，直接解锁并返回
    await unlockDocument()
    router.back()
  }
}

const handleSave = async () => {
  if (!document.value || saving.value) return

  saving.value = true
  try {
    const contentKey = {
      1: 'first_check',
      2: 'second_check',
      3: 'third_check'
    }[document.value.step]

    const result = await request.put(`/documents/${route.params.id}`, {
      [contentKey]: editContent.value
    })

    if (result.code === 200) {
      await unlockDocument()
      router.back()
    }
  } catch (error) {
    console.error('保存文档失败:', error)
  } finally {
    saving.value = false
  }
}

// 在组件销毁前解锁文档
onBeforeUnmount(async () => {
  await unlockDocument()
})

// 添加页面刷新/关闭时的解锁处理
const handleBeforeUnload = (e) => {
  // 尝试发送同步请求解锁
  const xhr = new XMLHttpRequest()
  xhr.open('POST', `/api/documents/${route.params.id}/unlock`, false)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.send()
  
  // 标准的beforeunload处理
  if (document.value && editContent.value !== getCurrentContent.value) {
    e.preventDefault()
    e.returnValue = ''
  }
}

onMounted(() => {
  fetchDocument()
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script> 